package com.hzsparrow.ai.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzsparrow.ai.entity.KnowledgeBase;
import com.hzsparrow.ai.entity.User;
import com.hzsparrow.ai.service.KnowledgeBaseService;
import com.hzsparrow.ai.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 知识库管理控制器
 */
@RestController
@RequestMapping("/api/knowledge-base")
public class KnowledgeBaseController {

    @Autowired
    private KnowledgeBaseService knowledgeBaseService;

    @Autowired
    private UserService userService;

    /**
     * 获取所有知识库列表
     */
    @GetMapping("/list")
    public ResponseEntity<?> getAllKnowledgeBases() {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            List<KnowledgeBase> knowledgeBases = knowledgeBaseService.getUserKnowledgeBases(user.getId());
            return ResponseEntity.ok(knowledgeBases);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取知识库列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取知识库详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getKnowledgeBase(@PathVariable Long id) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            KnowledgeBase knowledgeBase = knowledgeBaseService.getKnowledgeBase(id);
            
            // 验证访问权限
            if (!knowledgeBase.getCreateUserId().equals(user.getId()) && !user.getRole().equals("ROLE_ADMIN")) {
                return ResponseEntity.status(403).body("无权访问此知识库");
            }
            
            return ResponseEntity.ok(knowledgeBase);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取知识库详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建知识库
     */
    @PostMapping("/create")
    public ResponseEntity<?> createKnowledgeBase(@RequestBody KnowledgeBase knowledgeBase) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            knowledgeBase.setCreateUserId(user.getId());
            KnowledgeBase created = knowledgeBaseService.createKnowledgeBase(knowledgeBase);
            
            return ResponseEntity.ok(created);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("创建知识库失败: " + e.getMessage());
        }
    }

    /**
     * 更新知识库
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateKnowledgeBase(@PathVariable Long id, @RequestBody KnowledgeBase knowledgeBase) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 获取现有知识库
            KnowledgeBase existing = knowledgeBaseService.getKnowledgeBase(id);
            
            // 验证权限
            if (!existing.getCreateUserId().equals(user.getId()) && !user.getRole().equals("ROLE_ADMIN")) {
                return ResponseEntity.status(403).body("无权修改此知识库");
            }
            
            // 设置ID和创建者ID
            knowledgeBase.setId(id);
            knowledgeBase.setCreateUserId(existing.getCreateUserId());
            
            KnowledgeBase updated = knowledgeBaseService.updateKnowledgeBase(knowledgeBase);
            return ResponseEntity.ok(updated);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("更新知识库失败: " + e.getMessage());
        }
    }

    /**
     * 删除知识库
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteKnowledgeBase(@PathVariable Long id) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 获取知识库
            KnowledgeBase knowledgeBase = knowledgeBaseService.getKnowledgeBase(id);
            
            // 验证权限
            if (!knowledgeBase.getCreateUserId().equals(user.getId()) && !user.getRole().equals("ROLE_ADMIN")) {
                return ResponseEntity.status(403).body("无权删除此知识库");
            }
            
            boolean deleted = knowledgeBaseService.deleteKnowledgeBase(id);
            
            if (deleted) {
                return ResponseEntity.ok(Map.of("message", "知识库删除成功"));
            } else {
                return ResponseEntity.badRequest().body("知识库删除失败");
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("删除知识库失败: " + e.getMessage());
        }
    }

    /**
     * 获取知识库列表
     */
    @GetMapping
    public ResponseEntity<?> listKnowledgeBases(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long userId) {
        
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 管理员可以查看所有知识库，普通用户只能查看自己的
            if (!user.getRole().equals("ROLE_ADMIN") && (userId == null || !userId.equals(user.getId()))) {
                userId = user.getId();
            }
            
            Page<KnowledgeBase> result = knowledgeBaseService.listKnowledgeBases(page, size, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("total", result.getTotal());
            response.put("pages", result.getPages());
            response.put("current", result.getCurrent());
            response.put("size", result.getSize());
            response.put("records", result.getRecords());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error: " + e.getMessage());
        }
    }
} 